function init() {
    initChart();
    connect();
    sensor();
}
function showAlert(type, title, content) {
    // 简单实现，可根据需求用弹窗库等优化
    alert(`${title}: ${content}`); 
}
//开关锁
const switchLock = {
    101: false, // 空调（key=101）
    103: false, // 窗帘（key=103）
    104: false, // 音乐（key=104）
    304: false  // 摇篮（key=304）
};
// 显示当前时间
function updateTime() {
    const now = new Date();
    const options = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        weekday: 'long'
    };
    document.getElementById('timeDisplay').textContent = now.toLocaleDateString('zh-CN', options);
}
// 初始化时间并每秒更新
updateTime();
setInterval(updateTime, 1000);

// 温湿度数据存储
let tempData = [];
let humData = [];
let timeData = [];
let chart;

// tempData = [20, 21, 22, 23, 24];
// humData = [60, 62, 65, 70, 68];
// timeData = ['10:00:00', '10:01:00', '10:02:00', '10:03:00', '10:04:00'];
function initChart() {
    const chartDom = document.getElementById('tempHumChart');
    if (!chartDom) {
        console.error('图表容器未找到');
        return;
    }
    try {
        chart = echarts.init(chartDom);
        const option = {
            title: {
                text: '温湿度变化趋势',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            toolbox: {
                feature: {
                    dataView: { show: true, readOnly: false },
                    magicType: { show: true, type: ['line', 'bar'] },
                    restore: { show: true },
                    saveAsImage: { show: true }
                }
            },
            legend: {
                data: ['温度(°C)', '湿度(%)'],
                bottom: 10
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                top: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: timeData,
                axisLabel: {
                    formatter: function (value) {
                        return value ? value.split(' ')[1] : ''; // 错误：timeString没有空格
                    }
                }
            },
            yAxis: [
                {
                    type: 'value',
                    name: '温度(°C)',
                    min: 0,
                    max: 40,
                    axisLabel: {
                        formatter: '{value} °C'
                    }
                },
                {
                    type: 'value',
                    name: '湿度(%)',
                    min: 0,
                    max: 100,
                    axisLabel: {
                        formatter: '{value} %'
                    }
                }
            ],
            dataZoom: [{
                type: 'inside',
                start: 0,
                end: 100
            }, {
                start: 0,
                end: 100
            }],
            series: [
                {
                    name: '温度(°C)',
                    type: 'line',
                    smooth: true,
                    data: tempData,
                    yAxisIndex: 0,
                    markPoint: {
                        data: [
                            { type: 'max', name: '最高' },
                            { type: 'min', name: '最低' }
                        ]
                    },
                    lineStyle: {
                        width: 3,
                        color: '#c23531'
                    },
                    itemStyle: {
                        color: '#c23531'
                    }
                },
                {
                    name: '湿度(%)',
                    type: 'line',
                    smooth: true,
                    data: humData,
                    yAxisIndex: 1,
                    markPoint: {
                        data: [
                            { type: 'max', name: '最高' },
                            { type: 'min', name: '最低' }
                        ]
                    },
                    lineStyle: {
                        width: 3,
                        color: '#2f4554'
                    },
                    itemStyle: {
                        color: '#2f4554'
                    }
                }
            ]
        };
        chart.setOption(option);
        // 响应窗口大小变化
        window.addEventListener('resize', function () {
            chart.resize();
        });
        chart.setOption({
            series: [{
                data: []
            }, {
                data: []
            }]
        });
    } catch (e) {
        console.error('图表初始化失败:', e);
    }

}

// 更新图表数据
function updateChart(temp, hum) {
    if (!chart || isNaN(temp) || isNaN(hum)) {
        console.log('无效数据或图表未初始化');
        return;
    }
    const now = new Date();
    const timeString = now.toLocaleTimeString('zh-CN');

    // 添加到数据数组
    tempData.push(parseFloat(temp));
    humData.push(parseFloat(hum));
    timeData.push(timeString);

    // 保持最多50个数据点
    const maxDataPoints = 50;
    if (tempData.length > maxDataPoints) {
        tempData = tempData.slice(-maxDataPoints);
        humData = humData.slice(-maxDataPoints);
        timeData = timeData.slice(-maxDataPoints);
    }

    // 更新图表
    chart.setOption({
        xAxis: {
            data: timeData
        },
        series: [
            {
                data: tempData
            },
            {
                data: humData
            }
        ],
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                var time = params[0].name;
                var temp = params[0].value + '℃';
                var hum = params[1].value + '%';
                return `<div>时间：${time}</div><div>温度：${temp}</div><div>湿度：${hum}</div>`;
            }
        }
    });
}

function connect() {
    var xhr = new XMLHttpRequest();
    var url = "";
    xhr.open("post", url, true);
    var post_net = JSON.stringify({
        "type": 3,
    })
    // 监听请求状态变化
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var response = xhr.responseText;
            var info = JSON.parse(response)  //将json字符串反序列化为json对象  
            console.log(response);
            if (info.type == 3) {
                document.getElementById("host_name").textContent = info.http.host_name;
                document.getElementById("firm_ver").textContent = info.http.firm_ver;
                document.getElementById("ip").textContent = info.http.ip;
            }
        }
    };
    xhr.send(post_net);
}

//接收处理传感器数据，包括：温湿度、光照、声音、震动、摆动、空调
function sensor() {
    // while (true) {
    var xhr = new XMLHttpRequest();
    var url = "";
    xhr.open("post", url, true);
    var post_req = JSON.stringify({
        "type": 1,
        "limit": "all",
        "keys": [301, 302, 303, 304, 305, 101, 102, 103]
    });
    //301:温度 302：湿度 303：光照 304：摇篮 305：心率 101：空调 102：窗帘 103：音乐
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) { // 请求完成且成功
            var response = xhr.responseText; // 获取响应数据
            var info = JSON.parse(response)  //将json字符串反序列化为json对象
            console.log(info); // 在浏览器控制台打印响应数据
            //根据数据格式解析相应的值，后续还需处理数据类型等-------------------------
            if (info.type == 1) {
                var currentTemp, currentHum;
                for (var i = 0; i < info.data.length; i++) {
                    // console.log('data = ', info.data[i].val)
                    //体温
                    if (info.data[i].key == 301) {
                        currentTemp = parseFloat(info.data[i].value);
                        document.getElementById('tempValue').textContent = info.data[i].value + '℃';
                        if (Number(info.data[i].value) > 37) {
                            document.getElementById('tempDesc').textContent = "体温过高";
                            showAlert('warning', '体温异常', `当前体温${info.data[i].value}℃，已超过正常范围`);
                        } else if (Number(info.data[i].value) < 35) {
                            document.getElementById('tempDesc').textContent = "体温过低";
                            showAlert('warning', '体温异常', `当前体温${info.data[i].value}℃，已低于正常范围`);
                        }
                    }
                    //湿度
                    else if (info.data[i].key == 302) {
                        currentHum = parseFloat(info.data[i].value);
                        document.getElementById('humValue').textContent = info.data[i].value + '%';
                        if (Number(info.data[i].value) > 70) {
                            document.getElementById('humDesc').textContent = "湿度过高";
                            showAlert('warning', '湿度异常', `当前湿度${info.data[i].value}%，已超过正常范围`);
                        } else if (Number(info.data[i].value) < 60) {
                            document.getElementById('humDesc').textContent = "湿度过低";
                            showAlert('warning', '湿度异常', `当前湿度${info.data[i].value}%，已低于正常范围`);
                        }
                    }
                    //光照值
                    else if (info.data[i].key == 303) {
                        document.getElementById('lightValue').textContent = info.data[i].value + ' lux';
                        if (Number(info.data[i].value) > 20) {
                            document.getElementById('lightDesc').textContent = "光照过强";
                            showAlert('warning', '光照异常', `当前光照${info.data[i].value}lux，已超过正常范围,将关闭窗帘`);
                            document.getElementsByName('curtain')[0].checked=1;
                        } else if (Number(info.data[i].value) < 10) {
                            document.getElementById('lightDesc').textContent = "光照过弱";
                            showAlert('warning', '光照异常', `当前光照${info.data[i].value}lux，已低于正常范围`);
                        }
                    }
                    //心率
                    else if (info.data[i].key == 305) {
                        document.getElementById('heartValue').textContent = info.data[i].value + '次/分';
                        if (Number(info.data[i].value) > 100) {
                            document.getElementById('heartDesc').textContent = "心率过高";
                            showAlert('warning', '心率异常', `当前心率${info.data[i].value}次/分，已超过正常范围`);
                        } else if (Number(info.data[i].value) < 60) {
                            document.getElementById('heartDesc').textContent = "心率过低";
                            showAlert('warning', '心率异常', `当前心率${info.data[i].value}次/分，已低于正常范围`);
                        }
                    }
                    //环境温度
                    else if (info.data[i].key == 306) {
                        document.getElementById('envTempValue').textContent = info.data[i].value + '℃';
                        if (Number(info.data[i].value) > 30) {
                            document.getElementById('envTempDesc').textContent = "温度过高";
                        } else if (Number(info.data[i].value) < 15) {
                            document.getElementById('envTempDesc').textContent = "温度过低";
                        }
                    }

                    //按钮状态
                    //摇篮
                    else if (info.data[i].key == 304) {
                        // document.getElementsByName('cradle')[0].checked = Number(info.data[i].value);
                        if (!switchLock[304]) {
                            setCradleGear(Number(info.data[i].value));
                        }
                    }
                    //空调
                    else if (info.data[i].key == 101) {
                        if (!switchLock[101]) {
                            document.getElementsByName('aircondition')[0].checked = (info.data[i].value == "TRUE");
                            // document.getElementsByName('aircondition')[0].checked = Number(info.data[i].value);
                        }
                    }
                    //窗帘
                    else if (info.data[i].key == 103) {
                        if (!switchLock[103]) {
                            document.getElementsByName('curtain')[0].checked = (info.data[i].value == "TRUE");
                        }
                        // document.getElementsByName('curtain')[0].checked = Number(info.data[i].value);
                    }
                    //音乐
                    else if (info.data[i].key == 104) {
                        if (!switchLock[104]) {
                            document.getElementsByName('music')[0].checked = (info.data[i].value == "TRUE");
                        }
                        // document.getElementsByName('music')[0].checked = Number(info.data[i].value);
                    }
                    else if (info.data[i].key == 102) {
                        document.getElementById('tempDisplay').textContent = info.data[i].value + '°C';
                    }
                    // 如果同时有环境温度和湿度数据，则更新图表
                    if (currentTemp !== undefined && currentHum !== undefined) {
                        updateChart(currentTemp, currentHum);
                    }
                }
            }
        }
    };
    //将json对象序列化为json字符串
    xhr.send(post_req); // 发送请求，并将数据转换为JSON字符串
    // 10秒发送一次
    setTimeout(sensor, 2000);
}
//控制空调
function aircondition_contrl() {
    var aircondition = document.getElementById("aircondition");//空调开关
    var airValue = String(aircondition.checked ? 1 : 0);//空调
    var xhr = new XMLHttpRequest();
    var url = "";
    xhr.open("post", url, true);
    var post_req = JSON.stringify({
        "type": 2,
        "key": 101,
        "val": airValue,
        "equip": 2
    });
    switchLock[101] = true;
    setTimeout(() => { switchLock[101] = false; }, 2500);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            response = xhr.responseText;
            console.log(response);
        }
    };
    xhr.send(post_req);
}
//控制窗帘
function curtain_contrl() {
    var curtain = document.getElementById("curtain");//窗帘
    var curtainValue = String(curtain.checked ? 1 : 0);//窗帘
    var xhr = new XMLHttpRequest();
    var url = "";
    xhr.open("post", url, true);
    var post_req = JSON.stringify({
        "type": 2,
        "key": 103,
        "val": curtainValue,
        "equip": 2

    });
    switchLock[103] = true;
    setTimeout(() => { switchLock[103] = false; }, 2500);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            response = xhr.responseText;
            console.log(response);
        }
    };
    xhr.send(post_req);
}
//控制音乐
function music_contrl() {
    var music = document.getElementById("music");//音乐
    var musicValue = String(music.checked ? 1 : 0);//音乐
    var xhr = new XMLHttpRequest();
    var url = "";
    xhr.open("post", url, true);
    var post_req = JSON.stringify({
        "type": 2,
        "key": 104,
        "val": musicValue,
        "equip": 2
    });
    switchLock[104] = true;
    setTimeout(() => { switchLock[104] = false; }, 2500);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            response = xhr.responseText;
            console.log(response);
        }
    };
    xhr.send(post_req);
}
// 改变温度 
function changeTemperature(value) {
    document.getElementById('tempDisplay').textContent = value + '°C';
    var temp_airValue = String(value);//空调
    var xhr = new XMLHttpRequest();
    var url = "";
    xhr.open("post", url, true);
    var post_req = JSON.stringify({
        "type": 2,
        "key": 102,
        "val": temp_airValue,
        "equip": 2
    });
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            response = xhr.responseText;
            console.log(response);
        }
    };
    xhr.send(post_req);
}
// 空调开关切换
function toggleAirCondition(checkbox) {
    const tempControl = document.getElementById('temperatureControl');
    if (checkbox.checked) {
        tempControl.style.display = 'flex';
        console.log('空调已开启');
    } else {
        tempControl.style.display = 'none';
        console.log('空调已关闭');
    }
}
// 调整温度（增加或减少）
function adjustTemperature(delta) {
    const slider = document.getElementById('tempSlider');
    let newValue = parseInt(slider.value) + delta;
    // 确保温度在16-30度之间
    if (newValue < 16) newValue = 16;
    if (newValue > 30) newValue = 30;
    slider.value = newValue;
    changeTemperature(newValue);
}
// 设置特定温度
function setTemperature(temp) {
    const slider = document.getElementById('tempSlider');
    slider.value = temp;
    changeTemperature(temp);
}
// 摇篮档位控制函数
function setCradleGear(gear) {
    const gearButtons = document.querySelectorAll('.gear-btn');
    gearButtons.forEach(btn => btn.classList.remove('active'));
    const statusText = document.getElementById('cradleStatus');
    document.getElementsByName('cradle')[0].checked = (gear == 0 ? false : true);
    switch (gear) {
        case 0:
            statusText.textContent = '当前状态: 关闭';
            break;
        case 1:
            statusText.textContent = '当前状态: 低档';
            gearButtons[1].classList.add('active');
            break;
        case 2:
            statusText.textContent = '当前状态: 中档';
            gearButtons[2].classList.add('active');
            break;
        case 3:
            statusText.textContent = '当前状态: 高档';
            gearButtons[3].classList.add('active');
            break;
    }
}
function cradle_contrl(status) {
    setCradleGear(status);
    var cradleValue = String(status);
    var xhr = new XMLHttpRequest();
    var url = "";
    xhr.open("post", url, true);
    var post_req = JSON.stringify({
        "type": 2,
        "key": 304,
        "val": cradleValue,
        "equip": 1
    });
    switchLock[304] = true;
    setTimeout(() => { switchLock[304] = false; }, 2500);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            response = xhr.responseText;
            console.log(response);
        }
    };
    xhr.send(post_req);
}